package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Result;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/clazzs")
@RestController
public class ClazzController {

    @Autowired
    private ClazzService clazzService;

    @Autowired
    private EmpService empService;

    @GetMapping
    public Result list(String name,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end,
                       @RequestParam(defaultValue = "1") int page,
                       @RequestParam(defaultValue = "10") int pageSize) {
        log.info("查询班级列表");

        Page<Clazz> page1 = new Page<>(page,pageSize);
        //班级查询条件
        LambdaQueryWrapper<Clazz> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null,Clazz::getName,name);
        lqw.between(begin != null && end != null,Clazz::getBeginDate,begin,end);
        lqw.between(begin != null && end != null,Clazz::getEndDate,begin,end);
        Page<Clazz> page2 = clazzService.page(page1,lqw);

        PageResult<Clazz> pageResult = new PageResult<>(page2.getTotal(), page2.getRecords());
        //获取班级的信息
        List<Clazz> clazzes = page1.getRecords();
        for (Clazz clazz : clazzes) {
            if (clazz.getBeginDate() != null && clazz.getBeginDate().isAfter(LocalDate.now())){
                clazz.setStatus("未开课");
            }else if (clazz.getBeginDate() != null && LocalDate.now().isAfter(clazz.getBeginDate()) && LocalDate.now().isBefore(clazz.getEndDate())){
                clazz.setStatus("在读");
            }else if (clazz.getBeginDate() != null && LocalDate.now().isAfter(clazz.getEndDate())){
                clazz.setStatus("已结课");
            }
        }
        //获取班级id
        Set<Integer> idset = clazzes.stream().map(Clazz::getId).filter(Objects::nonNull).collect(Collectors.toSet());
        if (idset != null && idset.size() >0){
            //根据班级的id找到emp
            List<Emp> emps = empService.listByIds(idset);
            for (Clazz clazz : clazzes) {
                for (Emp emp : emps) {

                    if (emp != null&&emp.getId()!=null&&clazz.getMasterId().equals(emp.getId())){
                        clazz.setMasterName(emp.getName());
                    }
                }
            }
        }


        return Result.success(pageResult);
    }

    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public Result save(@RequestBody Clazz clazz) {
        log.info("新增班级：{}", clazz);
        clazz.setUpdateTime(LocalDateTime.now());
        clazzService.save(clazz);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("根据id查询班级：{}", id);

        Clazz clazz = clazzService.getById(id);
        //查询班主任信息
        Emp emp = empService.getById(id);

        clazz.setMasterName(emp.getName());

        return Result.success(clazz);
    }

    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public Result update(@RequestBody Clazz clazz) {
        log.info("修改班级：{}", clazz);

        clazzService.updateById(clazz);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    public Result delete(@PathVariable Integer id) {
        log.info("删除班级：{}", id);

        clazzService.removeById(id);
        return Result.success();
    }

    @GetMapping("/list")
    @Transactional(rollbackFor = Exception.class)
    public Result list() {
        log.info("查询全部班级");

        List<Clazz> list = clazzService.list();
        return Result.success(list);
    }
}
